<?php
namespace web\admin\controller;
class Category extends Common{
	private $db;
	public function __construct()
	{
		parent::__construct();
		$this->db=new \system\model\Category();
	}
	public function index(){
		$data = Data::tree($this->db->get(),'cname');
		View::with('data',$data);
		View::make();
	}

	/**
	 * @throws \Exception
	 * 添加
	 */
	public function add(){
		if (IS_POST){
			if ($this->db->store()){
				message('添加成功','','success');
			}else{
				message($this->db->getError(),'','error');
			}
		}
		$typeData=Db::table('vivo_type')->get();
		View::with('typeData',$typeData);
		View::make();
	}

	/**
	 * @throws \Exception
	 * 添加儿子子分类
	 */
	public function addSon(){
		$cid = q('get.cid',0,'intval');
		if (IS_POST){
			if ($this->db->store()){
				message('添加成功','','success');
			}else{
				message($this->db->getError(),'','error');
			}
		}
		$cateData = $this->db->where('cid',$cid)->field(['cid','cname','tid'])->first();
		View::with('cateData',$cateData);

		$typeData=Db::table('vivo_type')->get();
		View::with('typeData',$typeData);
		View::make();
	}

	/**
	 * @throws \Exception
	 * 修改
	 */
	public function edit(){
		if (IS_POST){
			if ($this->db->edit()){
				message('操作成功','','success');
			}
			message($this->db->getError(),'','error');
		}
		$cid = q('get.cid',0,'intval');
		$oldData = $this->db->where('cid',$cid)->first();
		$cateData = $this->db->getCateData($cid);
		$typeData=Db::table('vivo_type')->get();
		View::with('typeData',$typeData);
		View::with('oldData',$oldData)->with('cateData',$cateData)->make();
	}
	public function del(){
		$cid = q('get.cid',0,'intval');
		//pluck获取单一字段
		$pid = $this->db->where('cid',$cid)->pluck('pid');
		//删除父级 修改子层级 往上升一级
		$this->db->where('pid',$cid)->update(['pid'=>$pid]);
		$this->db->where('cid',$cid)->delete();
		message('删除成功',u('index'),'success');

	}
}
